import { exec } from "child_process";
import { app } from "electron";
import fs from "fs";
import Ftp from "ftp";
import { join } from "path";
import { isDev,PATH } from "../utils";

const ftpDir = "/files/05ToolsDevelopment/RenderDoc/Builds/development/";
const localDir = PATH.dataPath;
if(!fs.existsSync(localDir)){
  if(!fs.existsSync(`D:\\ProgramData`)){
    fs.mkdirSync(`D:\\ProgramData`)
  }
  fs.mkdirSync(localDir);
}
const ftpOptions = {
  host: "10.241.24.194",
  user: "graphic",
  password: "graphic",
};
// 解压之后保存文件的路径
const filePath = join(localDir, "./renderdoc");
// 7z应用文件路径
const exe7z = join(
  process.cwd(),
  isDev() ? "./plugins/7z/" : "./resources/plugins/7z/"
);

export const startRenderdoc = () => {
  return new Promise((resolve, reject) => {
    exec("qrenderdoc", { cwd: filePath }, (error, stdout, stderr) => {
      if (error) {
        reject(error);
        return;
      }
      resolve(stdout);
    });
  });
};

export const downloadRenderdoc = (win) => {
  return new Promise((resolve, reject) => {
    const ftp = new Ftp();
    ftp.on("ready", () => {
      ftp.list(ftpDir, (err, list) => {
        if (err) {
          reject(err);
          return;
        }
        list.sort((a, b) => {
          return new Date(a.date).getTime() - new Date(b.date).getTime();
        });
        const fileName = list[list.length - 1].name;
        const ftpFilePath = ftpDir + fileName;
        const localUrl = join(localDir, fileName);
        const totalSize = list[list.length - 1].size;
        let received = 0;
        ftp.get(ftpFilePath, (err, stream) => {
          if (err) {
            reject(err);
            return;
          }
          stream.on("data", (chunk) => {
            received += chunk.length;
            win.webContents.send(
              "download-progress",
              ((received / totalSize) * 100).toFixed(0)
            );
          });
          stream.once("close", () => {
            if (!fs.existsSync(localUrl)) {
              reject("不存在目标解压文件！");
              return;
            }
            if (fs.existsSync(join(filePath, "/qrenderdoc.exe"))) {
              reject("解压文件已存在！");
              return;
            }
            if (fs.existsSync(filePath)) {
              fs.rmdirSync(filePath);
            }
            fs.mkdirSync(filePath);
            // x: 完整路径下解压文件 -y：所有选项都为默认值 -o：设置输出目录
            exec(
              "7z x -y -o" + filePath + " " + localUrl,
              { cwd: exe7z },
              (error, stdout, stderr) => {
                if (error) {
                  reject(error);
                  return;
                }
                resolve(stdout);
              }
            );
          });
          stream.pipe(fs.createWriteStream(localUrl));
        });
      });
    });
    ftp.connect(ftpOptions);
  });
};

export const renderdocExist = () => {
  return fs.existsSync(join(filePath, "/qrenderdoc.exe"));
};

export const vcruntimeExist = () => {
  return (
    fs.existsSync("c:/Windows/System32/vcruntime140_1.dll") ||
    fs.existsSync("c:/Windows/System32/VCRUNTIME140_1.dll")
  );
};
